package com.deuwise.system.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.deuwise.common.utils.HttpContextUtils;
import com.deuwise.config.oauth2.JWTUtil;
import com.deuwise.system.entity.SysUser;
import com.deuwise.system.service.SysUserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Controller公共组件
 * 
 * @author chenwenchao
 * email chenwenchao@gmail.com
 * @date 2016年11月9日 下午9:42:26
 */
public abstract class AbstractController {
	protected Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private SysUserService sysUserService;
	protected SysUser getUser() {
		String token=(String)SecurityUtils.getSubject().getPrincipal();
		if(!org.apache.commons.lang3.StringUtils.isEmpty(token)) {
			String userId = JWTUtil.getUserId(token);
			SysUser user = sysUserService.selectById(userId);
			return  user;
		}
		return  null;
	}

	protected String getUserId() {
		String token=(String)SecurityUtils.getSubject().getPrincipal();
		if(token==null){
			return  "1";
		}
		String userId=JWTUtil.getUserId(token);
		return userId==null?"1":userId;
	}

	/**
	 * <pre>
	 * 自动获取分页参数，返回分页对象page
	 * </pre>
	 *
	 * <small> 2018年4月15日 | Aron</small>
	 *
	 * @param e
	 * @return
	 */
	public <E> Page<E> getPage(Class<E> e) {
		int pageNumber = getParaToInt("currentPage", 1);
		int pageSize = getParaToInt("pageSize", 10);
		return new Page<>(pageNumber, pageSize);
	}

	protected int getParaToInt(String key, int defalut) {
		String pageNumber = HttpContextUtils.getHttpServletRequest().getParameter(key);
		if (StringUtils.isBlank(pageNumber)) {
			return defalut;
		}
		return Integer.parseInt(pageNumber);
	}
}
